<template>
  <div class="field-item" style="padding-left:10px">
    <!-- <el-form-item class="hc-field-item" :label="titleLabel"> -->
    <!-- <a-upload action="https://www.mocky.io/v2/5cc8019d300000980a055e76" :multiple="false" :file-list="fileList" :loading="uploading" :remove="handleRemove" :before-upload="beforeUpload" :show-upload-list="false">
        <a-button>
          <a-icon type="upload" /> 上传正文
        </a-button>
      </a-upload> -->
    <!-- <div class="attachmentBox">
      <span v-for="(item,index) in fileList" :key="index">
        <a-button type="link" :title="item.name" @click="openWithWps(item)">{{ item.name.length > 30 ? item.name.substring(0, 30) + '...' : item.name }}</a-button>
        <div>
          <span class="btn-down" v-if="hiddenDownload" @click="handleDownload(item)">下载</span>
          <span class="btn-remove" v-if="!isZwTmp" @click="handleRemove(item)">删除</span>
        </div>
      </span>

    </div> -->
    <el-upload class="upload-demo" v-if="showUpload" action="" :before-upload="beforeUpload" :http-request="uploadFile" :show-file-list="false">
      <el-button class="button-new-tag" type="primary" icon="el-icon-plus" :loading="uploading">上传正文</el-button>
    </el-upload>
    <div class="file-list">
      <el-scrollbar class="scorll-Y" :style="{
          height: fileList.length > 6 ? '150px' : fileList.length * 25 + 'px',
        }">
        <div class="file-item" v-for="(item, index) in fileList" :key="index">
          <div style="cursor: pointer;">
            <i class="el-icon-link"></i>
            <el-tooltip popper-class="hc-dec-text" v-if="item.name.length > filenameLength" :content="item.name" placement="top" effect="light">
              <span class="filename" type="link" @click="openWithWps(item)">{{
                item.name.substring(0, filenameLength) + "..."
              }}</span>
            </el-tooltip>
            <span v-else class="filename" type="link" :title="item.name" @click="openWithWps(item)">{{ item.name }}</span>
          </div>
          <div>
            <span class="btn-down" v-if="!hiddenDownload" @click="handleDownload(item)">下载</span>
            <span class="btn-remove" v-if="showDelete" @click="handleRemove(item)">删除</span>
          </div>
        </div>
      </el-scrollbar>
    </div>

  </div>
</template>
<script>
import { getOpenOfdDownloadUrl, uploadPrintResult } from '../api/common/attachment'
import { getList as getWordFilesList, getDownloadZBUrl, openUploadZB, delWordFiles } from '../api/common/wordfiles'
import
{
  getList as getFileDataList,
  getDownloadUrl as getFileDataDownloadUrl
} from "../api/common/filedata";
import { formatDate } from '../utils/index';
import { Loading } from 'element-ui';
export default {
  name: 'GZUpload',
  props: ['relationUnid', 'showUpload', 'hiddenDownload', 'showDelete', 'formType', 'moduleName'],
  data()
  {
    return {
      uploading: false,
      titleLabel: '',
      filenameLength: window.HC_config.VUE_SHOW_FILENAME_LENGTH || 30,
      // 上传时wps文件改成office文件
      fileWpsToOffice: window.HC_config.VUE_APP_UPLOAD_WPS_TO_OFFICE || false,
      fileList: [],
      headers: {
        authorization: 'authorization-text'
      },
      sessionID: '',
      websocket: null,
      formData: {},
      // 打印编号
      printCode: 1,
      mborgUnid: ''
    }
  },
  watch: {
  },
  activated()
  {
  },
  mounted()
  {
  },
  created()
  {
    this.getData()
    this.sessionID = this.getID(8)
    setTimeout(() =>
    {
      var wsUri = window.HC_config.VUE_FX_WEBSOCKET_BASE_URL + '/webSocket/' + this.sessionID;
      this.startWebSocket(wsUri)
    }, 500)
    this.formData = this.$parent.getFormParam()
    this.printCode = this.formData.printCode;
    this.mborgUnid = this.formData.mborgUnid;
    console.log(this.formData, 'formData')
  },
  methods: {
    getData()
    {
      if (typeof (this.relationUnid) == 'undefined')
      {
        return
      }
      getWordFilesList({ parentUnid: this.relationUnid }).then(res =>
      {
        if (res.code == 200)
        {
          this.fileList = []
          res.result.data.map(item =>
          {
            var file = {}
            file.name = item.attachName;
            file.status = 'done';
            file.parentUnid = item.parentUnid;
            file.uid = item.unid;
            file.url = item.url;
            this.fileList.push(file)
          })
        }
      })
    },
    beforeUpload(file)
    {
      //  手动上传
      this.uploadFile(file)
      return false
    },
    uploadFile(file)
    {
      if (this.fileWpsToOffice)
      {
        const splits = file.name.split(".");
        const name = splits[0];
        const suffix = (splits[1] || "").toLowerCase();
        if (suffix && ['wps', 'et'].includes(suffix))
        {
          const fileSuffix = suffix == 'wps' ? "docx" : "xlsx";
          let f = new File([file], `${name}.${fileSuffix}`);
          f.uid = file.uid; // new File 没有uid属性，会导致组件底层报错，这里手动加上
          file = f;
        }
      }
      const formData = new FormData()
      formData.append('file', file)
      this.uploading = true
      const loading = Loading.service({
        lock: true,
        text: "正在上传中....", //办结中 或定稿中
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      });
      openUploadZB(this.relationUnid, formData, progress =>
      {
        console.log(progress)
      })
        .then(res =>
        {
          if (res.code == 200)
          {
            this.$message.success('正文上传成功')
            this.getData()
          } else if (res.message == 'filename : [chrome.exe], extension : [exe], allowed extension : [[bmp, gif, jpg, jpeg, png, doc, docx, xls, xlsx, ppt, pptx, html, htm, txt, rar, zip, gz, bz2, pdf]]')
          {
            this.$message.error('文件格式不受支持，请更换')
          } else
          {
            this.$message.error(res.message)
          }
        })
        .catch(error =>
        {
          if (error)
          {
            this.$message.error('系统错误，请稍后再试')
            this.uploading = false
          }
        })
        .finally(() =>
        {
          loading.close();
          this.uploading = false
        })
    },
    // 下载
    async handleDownload(file)
    {
      //盖章正文列表
      let gzDocListRes = await getFileDataList({
        parentUnid: this.relationUnid,
      })
      if (gzDocListRes.result && gzDocListRes.result.data.length > 0)
      {
        //有盖章正文
        let openurl = getFileDataDownloadUrl(this.relationUnid);
        window.open(openurl);
      }
      else
      {
        //无盖章正文 下载正文
        window.open(getDownloadZBUrl(file.uid));
      }
    },
    async openWithWps(file)
    {
      //盖章正文列表
      let gzDocListRes = await getFileDataList({
        parentUnid: this.relationUnid,
      })
      if (gzDocListRes.result && gzDocListRes.result.data.length > 0)
      {
        //有盖章正文
        let openurl = getFileDataDownloadUrl(this.relationUnid);
        window.open("/filepreview?url=" + encodeURIComponent(openurl) + "&fileType=pdf&fileName=" + file.name + "&formType=" + this.formType + "&moduleName=" + this.moduleName);
      }
      else
      {
        let VUE_APP_BASE_API = localStorage.getItem("local_server_ip") || window.HC_config.VUE_APP_BASE_API || process.env.VUE_APP_BASE_API;
        if (file.name.indexOf('.xls') != -1)
        {
          this.$message.warning("Excel文件不支持直接打开，请下载后查看")
          return;
        }
        else if (file.name.toLowerCase().indexOf('.ofd') != -1 || file.name.toLowerCase().indexOf('.gd') != -1)
        {
          //ofd文件用数科打开
          if (typeof this.$parent.$parent === "object" && this.$parent.$parent.formBase.formName == 'gwcs')
          {
            if (window.HC_config.VUE_APP_OPEN_OFD)
            {
              // 判断电脑系统 window调用在线打开pdf  否则用福昕打开
              var agent = localStorage.getItem('agentOS')
              if (agent && agent == 'window')
              {
                window.open(`/zxfw/ofdview.html?file=${file.unid}`)
                return;
              }
              else
              {
                var filePath = getOpenOfdDownloadUrl(file.uid)
                console.log(filePath, 'filePath')
                // var printCode = this.formData.printCode;  // 打印編號
                var maxPrintCopies = this.formData.syfs;  // 打印份数
                var markText = this.$store.getters.userInfo.personCommonname + ' ' + formatDate(new Date(), '{y}-{m}-{d}');
                // var markText = this.$store.getters.userInfo.personCommonname;
                filePath = window.btoa(filePath)
                var addWaterMarkTxt = encodeURI(`${markText},10,10,30,20,仿宋_GB2312,14,FF0000,all,1,20,20;${markText},10,100,30,20,仿宋_GB2312,14,FF9900,all,1,20,20`);
                addWaterMarkTxt = decodeURI(addWaterMarkTxt);
                var addWatermarkCopies = decodeURI(`1,5,5,0,100,仿宋_GB2312,16,FF0000,all,0,20,20`)
                var link = document.createElement('a');
                if (this.printCode != null || this.printCode != undefined)
                {
                  link.href = `kpofd://openUrl=${filePath}&fCompUnVisible=open,save,saveas,snapshot,hand,uploadfile,clipprint,selecttext&fCompEnable=print&AddWaterMarkTxt=${addWaterMarkTxt}&sessionID=${this.sessionID}&printInitialCopies=${this.printCode}&printMaxCopies=${maxPrintCopies}&AddWatermarkCopies=${addWatermarkCopies}`;
                }
                else
                {
                  link.href = `kpofd://openUrl=${filePath}&fCompUnVisible=open,save,saveas,snapshot,hand,uploadfile,clipprint,selecttext&AddWaterMarkTxt=${addWaterMarkTxt}&sessionID=${this.sessionID}`
                }
                console.log(link.href, 'kpofd地址')
                link.click();
              }
            }
            else
            {
              // window.open("/zxfw/ofdgwcs.html?unid=" + file.uid)
              window.open(`/zxfw/ofdview.html?file=${file.unid}`)
              return;
            }
          } else
          {
            // window.open("/zxfw/ofd.html?unid=" + file.uid)
            window.open(`/zxfw/ofdview.html?file=${file.unid}`)
            return;
          }
        }
        else if ((window.HC_config.VUE_APP_WINDOW_FILE_PREVIEW
          || window.HC_config.VUE_APP_SINGLE_FILE_PREVIEW)
          && (file.name.toLowerCase().indexOf('.doc') != -1
            || file.name.toLowerCase().indexOf('.docx') != -1
            || file.name.toLowerCase().indexOf('.pdf') != -1))
        {
          let url = "";
          let split = file.name.split(".");
          let fileType = (split[1] || "").toLowerCase();
          if (fileType.toLowerCase() == "pdf")
          {
            url = VUE_APP_BASE_API + "/gwfj/wordfile/download/" + file.uid;
          } else
          {
            url = VUE_APP_BASE_API + "/sign/contract/showFile/?unid=" + file.parentUnid + "#download=0"
          }
          window.open("/filepreview?url=" + encodeURIComponent(url) + "&fileType=" + fileType + "&fileName=" + file.name + "&formType=" + this.formType + "&moduleName=" + this.moduleName);
        }
        else if (file.name.toLowerCase().indexOf('.pdf') != -1)
        {
          // 用福昕打开加水印
          if (
            window.HC_config.VUE_APP_OPEN_PDF
          )
          {
            // 判断电脑系统 window调用在线打开pdf  否则用福昕打开
            var agent = localStorage.getItem('agentOS')
            if (agent && agent == 'window')
            {
              window.open("/showpdf?type=wordfile&unid=" + file.uid + "&showWatermask=" + window.HC_config.VUE_APP_PDF_WATERMARK)
              return;
            }
            else
            {
              var filePath = getOpenOfdDownloadUrl(file.uid)
              console.log(filePath, 'filePath')
              // var printCode = this.formData.printCode;  // 打印編號
              var maxPrintCopies = this.formData.syfs;  // 打印份数
              var markText = this.$store.getters.userInfo.personCommonname + ' ' + formatDate(new Date(), '{y}-{m}-{d}');
              // var markText = this.$store.getters.userInfo.personCommonname;
              filePath = window.btoa(filePath)
              var addWaterMarkTxt = encodeURI(`${markText},10,10,30,20,仿宋_GB2312,14,FF0000,all,1,20,20;${markText},10,100,30,20,仿宋_GB2312,14,FF9900,all,1,20,20`);
              addWaterMarkTxt = decodeURI(addWaterMarkTxt);
              var addWatermarkCopies = decodeURI(`1,5,5,0,100,仿宋_GB2312,16,FF0000,all,0,20,20`)
              var link = document.createElement('a');
              if (this.printCode != null || this.printCode != undefined)
              {
                link.href = `kpofd://openUrl=${filePath}&fCompUnVisible=open,save,saveas,snapshot,hand,uploadfile,clipprint,selecttext&fCompEnable=print&AddWaterMarkTxt=${addWaterMarkTxt}&sessionID=${this.sessionID}&printInitialCopies=${this.printCode}&printMaxCopies=${maxPrintCopies}&AddWatermarkCopies=${addWatermarkCopies}`;
              }
              else
              {
                link.href = `kpofd://openUrl=${filePath}&fCompUnVisible=open,save,saveas,snapshot,hand,uploadfile,clipprint,selecttext&AddWaterMarkTxt=${addWaterMarkTxt}&sessionID=${this.sessionID}`
              }
              console.log(link.href, 'kpofd地址')
              link.click();
            }
          }
          else
          {
            window.open("/showpdf?type=wordfile&unid=" + file.uid + "&showWatermask=" + window.HC_config.VUE_APP_PDF_WATERMARK)
            return;
          }
        } else
        {
          viewDocument(
            VUE_APP_BASE_API,
            file.uid,
            ""
          );
        }
      }

    },
    // 开启websocket消息
    startWebSocket(wsUri)
    {
      if (this.websocket)
      {
        //关闭先前的websocket
        this.closeWebSocket();
      }
      let self = this;
      this.websocket = new WebSocket(wsUri);
      this.websocket.onopen = function (evt)
      {
        console.log("连接成功success");
      };
      this.websocket.onmessage = this.onMessage;
      this.websocket.onerror = function (evt) { };
      this.websocket.onclose = function (evt) { };
    },
    //关闭websocket
    closeWebSocket()
    {
      if (this.websocket)
      {
        this.websocket.close(1000, "Work complete");
      }
    },
    /**
     * 监听webSoket消息
     */
    onMessage(P_Evt)
    {
      var obj = JSON.parse(P_Evt.data);
      console.log(obj, '监听消息')
      if (obj.action == 'getPrintPermission')
      {
        console.log('打印前')
        this.doSend('1')
        // 如果没有权限不能继续打印发送0
        // getPrintPermission({unid: this.$route.query.unid}).then(res => {
        //   console.log(res, '打印前回调')
        //   if (res.code == 200)
        //   {
        //     this.printMaxCopies = res.result
        //   }
        //   else
        //   {
        //     this.$message.warning(res.message)
        //     this.doSend('0')
        //   }
        // })
      }
      else if (obj.action == 'uploadPrintResult')
      {
        console.log("打印后")
        var param = {
          unid: this.$route.query.unid,
          dyfs: obj.current,
          mborgUnid: this.mborgUnid
        }
        uploadPrintResult(param).then(res =>
        {
          console.log(res, '打印后回调')
          var syfs = parseInt(Number(this.formData.syfs) - Number(obj.current))
          console.log(syfs, '打印后剩余份数')
          if (syfs > 0)
          {
            this.printCode = Number(this.formData.printCode++)
            console.log(printCode, '打印后递增编号')
            this.$parent.fieldChangeHandle(["syfs", syfs])
            this.$parent.fieldChangeHandle(["printCode", this.printCode])
            this.$parent.reaLoadForm()
          }
          else
          {
            this.$message.warning('没有剩余份数可打印了')
            this.doSend('0')
          }
        })
      }
    },
    //发送消息
    doSend(message)
    {
      console.log("-----发送消息打开福昕------")
      console.log(this.websocket.readyState)
      console.log("-----发送消息打开福昕------")
      if (this.websocket.readyState == 1)
      {
        this.websocket.send(message);
      }
    },
    getID(length)
    {
      return Number(Math.random().toString().substr(3, length) + Date.now()).toString(36);
    },
    handleChange(info)
    {
      let fileList = [...info.fileList]
      fileList = fileList.slice(-2)
      fileList = fileList.map(file =>
      {
        console.log('file.response', file.response)
        if (file.response)
        {
          file.name = res.response.fileName,
            file.status = 'done',
            file.parentUnid = res.response.parentUnid;
          file.uid = res.response.unid
          file.url = file.response.url
        }
        return file
      })
      this.fileList = fileList
    },
    handleRemove(file)
    {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() =>
        {
          delWordFiles({ unids: file.uid }).then(res =>
          {
            this.$message.success('正文删除成功')
            const index = this.fileList.indexOf(file)
            const newFileList = this.fileList.slice()
            newFileList.splice(index, 1)
            this.fileList = newFileList

          }).catch(err =>
          {
            console.log(err)
          })
        })
    }
  },
  computed: {
  }
}
</script>
<style scoped lang="scss">
.file-list {
  display: flex;
  flex-direction: column;
  .file-item {
    width: 100%;
    line-height: 1.3em;
    // justify-content: space-between;
    align-items: center;
    display: flex;
    font-size: 14px;
    color: #409eff;
    margin-top: 5px;
    .el-icon-link {
      font-size: 18px;
      margin-right: 5px;
      transform: translateY(2px);
    }
    .btn-down {
      color: #409eff;
      cursor: pointer;
      margin-left: 20px;
    }
    .btn-remove {
      color: #f56c6c;
      cursor: pointer;
      margin-left: 10px;
    }
  }
}

.scorll-Y ::v-deep .el-scrollbar__wrap {
  overflow-x: hidden;
}

.button-new-tag {
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
</style>
